package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.fastdfs.FastDfsClient;
import com.atguigu.gmall.common.result.Result;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传controller
 */
@RestController
@RequestMapping(value = "/admin/product/fileUpload")
public class FileController {
    @Value("${fileServer.url}")
    private String fileUrl;

    @Autowired
    private FastDfsClient fastDfsClient;

    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception{
//        //加载配置文件
//        ClassPathResource classPathResource = new ClassPathResource("fast_dfs.conf");
//        //初始化fastdfs对象
//        ClientGlobal.init(classPathResource.getPath());
//        //初始化trackerclient
//        TrackerClient trackerClient = new TrackerClient();
//        //获得服务器连接信息
//        TrackerServer connection = trackerClient.getConnection();
//        //初始化storageClient
//        StorageClient storageClient = new StorageClient(connection, null);
//        //获取文件扩展名
//        String fileName = StringUtils.getFilenameExtension(file.getOriginalFilename());
//        /*
//        * 1.文件字节码
//        * 2.文件拓展名
//        * 3.附加参数
//        * 4.返回结果为数组:0:组名  1:文件的完全路径名+文件名
//        * */
//        String[] strings = storageClient.upload_file(file.getBytes(), fileName, null);
//        //返回文件全量访问路径
//        return Result.ok(fileUrl +strings[0] +"/"+strings[1]);
        String path = fastDfsClient.upload(file);
        return Result.ok(fileUrl+path);
    }
}
